package com.aerozhonghuan.logisticsmall.framework.hybrid.actions;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import com.aerozhonghuan.logisticsmall.framework.hybrid.NewWebviewFragment;
import com.aerozhonghuan.logisticsmall.framework.hybrid.SimpleActionHandler;
import com.aerozhonghuan.logisticsmall.framework.hybrid.bean.JsMobileAgentConstants;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.hybrid.XJsCallback;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 描述
 * 作者 Zhang Yonghui
 * 创建日期 2019/1/21
 */
public class ScreenshotActionHandler extends SimpleActionHandler {
    private static final String TAG = "ScreenshotActionHandler";
    private static final String KEY_MARGIN = "margin";
    private static final String KEY_LEFT = "left";
    private static final String KEY_TOP = "top";
    private static final String KEY_WIDTH = "width";
    private static final String KEY_HEIGHT = "height";

    public ScreenshotActionHandler(NewWebviewFragment fragment) {
        super(JsMobileAgentConstants.FLAG_SCREENSHOT, fragment);
    }

    @Override
    public void handleAction(@NonNull String action, @Nullable JSONObject params, @Nullable XJsCallback callBack) {
        String left;
        String top;
        String width;
        String height;
        View dView = getActivity().getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap drawingCache = dView.getDrawingCache();
        if (params != null && params.has(KEY_MARGIN) && params.optJSONObject(KEY_MARGIN) != null) {
            // 截取某个区域
            JSONObject margin = params.optJSONObject(KEY_MARGIN);
            left = margin.optString(KEY_LEFT);
            top = margin.optString(KEY_TOP);
            width = margin.optString(KEY_WIDTH);
            height = margin.optString(KEY_HEIGHT);
            LogUtil.d(TAG, String.format("left::%s  top::%s  width::%s  height::%s", left, top, width, height));
            int screenWidth = drawingCache.getWidth();
            int screenHeight = drawingCache.getHeight();
            int webviewHeight = getFragment().getWebView().getHeight();
            LogUtil.d(TAG, String.format("屏幕宽度::%s  屏幕高度::%s  web高度::%s", screenWidth, screenHeight, webviewHeight));
            // 获取titlebar和状态栏高度比例(由于js获取的屏幕宽高为手机屏幕宽高实际单位,例如360 748,比例为整屏的宽高比,而获取元素top为距离webview的高度
            double titleHeight = (double) (screenHeight - webviewHeight) / screenHeight;
            saveAlum(Bitmap.createBitmap(drawingCache, (int) (screenWidth * Double.valueOf(left)), (int) (screenHeight * (Double.valueOf(top) + titleHeight)), (int) (screenWidth * Double.valueOf(width)), (int) (screenHeight * Double.valueOf(height))));
        } else {
            saveAlum(Bitmap.createBitmap(drawingCache));
        }
    }

    /**
     * 保存到手机相册
     * @param bitmap
     */
    private void saveAlum(Bitmap bitmap){
        if (bitmap != null) {
            String bitName = System.currentTimeMillis() + ".jpg";
            // 图片文件路径
            String path = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
            File mkPath = new File(path);

            String filePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
            File file = new File(filePath);
            try {
                if (!mkPath.exists()) {
                    mkPath.mkdirs();
                }
                FileOutputStream out;
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
                getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filePath)));
                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
